package cn.com.wangluotongxin.service.controller;

import cn.com.wangluotongxin.admin.model.constants.SmsAppInfo;
import cn.com.wangluotongxin.common.eureka.constants.SmsTemplate;
import cn.com.wangluotongxin.common.eureka.form.AuthPhoneCodeForm;
import cn.com.wangluotongxin.common.eureka.form.SendPhoneCodeForm;
import cn.com.wangluotongxin.common.eureka.form.SendSmsForm;
import cn.com.wangluotongxin.common.web.AjaxResult;
import cn.com.wangluotongxin.service.service.IAdminPhoneCodeService;
import cn.com.wangluotongxin.service.service.IAdminSmsPushService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "通用服务 内部接口")
@RestController
@RequestMapping("/inner")
public class InnerController {

    @Autowired
    private IAdminSmsPushService smsPushService;

    @Autowired
    private IAdminPhoneCodeService phoneCodeService;

    @ApiOperation("发送短信")
    @PostMapping("/send/sms")
    public AjaxResult sendSms(@RequestBody SendSmsForm form){
        Assert.notNull(form.getAppInfo(), "缺少应用类型");
        SmsAppInfo appInfo = SmsAppInfo.getByCode(form.getAppInfo());
        Assert.notNull(appInfo, "应用类型不存在");
        Assert.isTrue(StrUtil.isNotBlank(form.getTemplate()), "请选择签名模板");
        SmsTemplate smsTemplate = SmsTemplate.getByName(form.getTemplate());
        Assert.notNull(smsTemplate, "签名模板不存在");
        Assert.isTrue(StrUtil.isNotBlank(form.getPhone()), "缺少手机号");
        Assert.notNull(form.getExpireTime(), "缺少过期时间");

        smsPushService.addCodeSms(appInfo, smsTemplate, form.getPhone(), form.getExpireTime(), RandomUtil.randomNumbers(4));
        return AjaxResult.success();
    }

    @ApiOperation("发送验证码")
    @PostMapping("/send/phone/code")
    public AjaxResult sendPhoneCode(@RequestBody SendPhoneCodeForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getPhone()), "缺少手机号");

        phoneCodeService.sendPhoneCode(form.getPhone());
        return AjaxResult.success("发送成功");
    }

    @ApiOperation("验证码效验")
    @PostMapping("/auth/phone/code")
    public AjaxResult authPhoneCode(@RequestBody AuthPhoneCodeForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getPhone()), "缺少手机号");
        Assert.isTrue(StrUtil.isNotBlank(form.getCode()), "缺少验证码");

        phoneCodeService.authPhoneCode(form.getPhone(), form.getCode());
        return AjaxResult.success("验证码正确");
    }
}
